package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/validation"
	httpfacade "github.com/hulutech-web/http_result"
	"goravel/app/http/requests"
	"goravel/app/http/resources"
	"goravel/app/models/systemEntity"
	"goravel/app/models/userEntity"
)

type AuthController struct {
	// Dependent services
}

func NewAuthController() *AuthController {
	return &AuthController{
		// Inject services
	}
}

// Login manager login.管理员登录
// @Summary 管理员登录
// @Description 登录，管理员通过提交 JSON 格式数据进行登录。
// @Tags AuthController
// @Accept json
// @Produce json
// @Id 	AuthLogin
// @Param loginData body requests.UserLoginRequest true "登录数据，包含手机号码和密码"
// @Success 200 {string} json {}
// @OperationID Login
// @Router   /api/login [post]
func (r *AuthController) Login(ctx http.Context) http.Response {
	var user_req requests.UserLoginRequest
	ctx.Request().Bind(&user_req)
	password := user_req.Password
	//验证
	validator, _ := facades.Validation().Make(map[string]any{
		"account":  ctx.Request().Input("account", ""),
		"password": ctx.Request().Input("password", ""),
	}, map[string]string{
		"account":  "required",
		"password": "required",
	}, validation.Messages(map[string]string{
		"account.required":  "账号不能为空",
		"password.required": "密码不能为空",
	}))
	if validator.Fails() {
		return httpfacade.NewResult(ctx).ValidError("用户名或密码错误", nil)
	}
	var user userEntity.User
	//手机号密码验证
	facades.Orm().Query().Model(&user).Where("phone=?", user_req.Account).OrWhere("username=?", user_req.Account).First(&user)

	if user.ID == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "用户不存在", nil)
	}
	var user_exist userEntity.User
	facades.Orm().Query().Model(&userEntity.User{}).Where("id=?", user.ID).
		With("Roles").First(&user_exist)
	if !facades.Hash().Check(password, user_exist.Password) {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "密码错误", nil)
	} else {
		//	生成token
		token, err1 := facades.Auth(ctx).Login(&user_exist)
		if err1 != nil {
			return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "服务器错误", nil)
		}
		userResp := resources.UserResp{
			Username:       user_exist.Username,
			RealName:       user_exist.RealName,
			Birthday:       user_exist.Birthday,
			CardId:         user_exist.CardId,
			Mark:           user_exist.Mark,
			GroupID:        user_exist.GroupID,
			Nickname:       user_exist.Nickname,
			Phone:          user_exist.Phone,
			AddIp:          user_exist.AddIp,
			LastTime:       user_exist.LastTime,
			NowMoney:       user_exist.NowMoney,
			BrokerageMoney: user_exist.BrokerageMoney,
			Integral:       user_exist.Integral,
			Exp:            user_exist.Exp,
			SignNum:        user_exist.SignNum,
			Status:         user_exist.Status,
			Level:          user_exist.Level,
			UserType:       user_exist.UserType,
			IsDelivery:     user_exist.IsDelivery,
			PayCount:       user_exist.PayCount,
			Address:        user_exist.Address,
			AdminID:        user_exist.AdminID,
			LoginType:      user_exist.LoginType,
			Avatar:         user_exist.Avatar,
			StaffID:        user_exist.StaffID,
			InviteCode:     user_exist.InviteCode,
		}
		role_names := []string{}
		for _, role := range user_exist.Roles {
			role_names = append(role_names, role.Value)
		}
		userResp.Roles = role_names
		return ctx.Response().Status(http.StatusOK).Json(http.Json{
			"message": "登录成功",
			"data": struct {
				Token string             `json:"token"`
				User  resources.UserResp `json:"user"`
			}{
				Token: token,
				User:  userResp,
			},
		})
	}
}

func (r *AuthController) DeliveryLogin(ctx http.Context) http.Response {
	var user_req requests.UserLoginRequest
	ctx.Request().Bind(&user_req)
	password := user_req.Password
	//验证
	validator, _ := facades.Validation().Make(map[string]any{
		"mobile":   ctx.Request().Input("mobile", ""),
		"password": ctx.Request().Input("password", ""),
	}, map[string]string{
		"mobile":   "required",
		"password": "required",
	}, validation.Messages(map[string]string{
		"mobile.required":   "名称不能为空",
		"password.required": "密码不能为空",
	}))
	if validator.Fails() {
		return httpfacade.NewResult(ctx).ValidError("用户名或密码错误", nil)
	}
	var user userEntity.User
	//手机号密码验证
	facades.Orm().Query().Model(&user).Where("mobile", user_req.Account).First(&user)

	if user.ID == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "用户不存在", nil)

	}
	var user_exist userEntity.User
	facades.Orm().Query().Model(&user_exist).With("Roles").Where("mobile", user_req.Account).First(&user_exist)

	if len(user_exist.Roles) == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "非送货员角色", nil)
	}
	role := user_exist.Roles[0]
	facades.Orm().Query().Model(&systemEntity.Role{}).Where("id=?", role.ID).With("Site").Find(&role)
	if !facades.Hash().Check(password, user_exist.Password) {
		return ctx.Response().Status(http.StatusInternalServerError).Json(http.Json{
			"message": "密码错误",
		})
	} else {
		//	生成token
		token, err1 := facades.Auth(ctx).Login(&user_exist)
		if err1 != nil {
			return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "服务器错误", nil)
		}

		return ctx.Response().Status(http.StatusOK).Json(http.Json{
			"message": "登录成功",
			"data": struct {
				Token string            `json:"token"`
				User  userEntity.User   `json:"user"`
				Role  systemEntity.Role `json:"role"`
			}{
				Token: token,
				User:  user_exist,
				Role:  role,
			},
		})
	}
}

// Logout manager login.管理员退出
// @Summary 管理员退出
// @Description 管理员退出。
// @Tags AuthController
// @Accept json
// @Produce json
// @Id AuthLogout
// @Success 200 {string} json {}
// @OperationID Login
// @Router   /api/logout [get]
func (r *AuthController) Logout(ctx http.Context) http.Response {
	err := facades.Auth(ctx).Logout()
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "退出失败", err.Error())
	}
	return httpfacade.NewResult(ctx).Success("退出成功", nil)
}
